﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace Sapphire.Linq.Framework
{
    public abstract class QueryProvider : IQueryProvider
    {
        IQueryable IQueryProvider.CreateQuery(Expression expression)
        {
            Type elementType = TypesHelper.GetEntityType(expression.Type);
            try
            {
                return (IQueryable)Activator.CreateInstance(typeof(Query<>).MakeGenericType(elementType), new object[] { this, expression });
            }
            catch (TargetInvocationException tie)
            {
                throw tie.InnerException;
            }
        }

        object IQueryProvider.Execute(Expression expression)
        {
            return Execute(expression);
        }

        public abstract IQueryable<TElement> CreateQuery<TElement>(Expression expression);
        public abstract object Execute(Expression expression);
        public abstract T Execute<T>(Expression expression);
    }
}